#!/usr/bin/env python
# encoding: utf-8
"""
thingsplot.py

Created by Christopher Glasman on 2009-04-08.
Copyright (c) 2009 Christopher Glasman. 

This file is part of thingsplot.

thingsplot is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

thingsplot is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with thingsplot.  If not, see <http://www.gnu.org/licenses/>.

"""

import sys
import os
from ThingsDatabase import ThingsDatabase
from ThingsProject import ThingsProject
import datetime
import time
from matplotlib import pyplot,dates
from numpy import *


def main(filename, pid="general"):
    VERBOSE=0
    #
    # load and do an initial parse of the Things XML Database.
    db = ThingsDatabase(filename)
    # loop through the database to find the defined Projects.
    db.find_projects()
    # db.show_projects()
    #
    # loop through the database and attach Todo items to projects and
    # record timestamp data. 
    db.find_todo_items()
    print "=========================="
    # db.show_projects()
    if(pid == "general"):
        #
        #select the last created project in db i.e. the general items "project". 
        pid=len(db.project_list)-1
    print "Extracting data for project: ", db.project_list[pid].title
    print "=========================="
    if(VERBOSE==1):
        #
        #list all items in the project
        db.project_list[pid]._print_()
    days_created = db.project_list[pid].get_dates_created()
    # print days
    days_comp = db.project_list[pid].get_dates_completed()
    print "number of completed items: ", len(days_comp)
    # print days_comp
    days = array(days_created)
    # print days
    days_comp = array(days_comp)
    #
    #get the outstanding stuff
    d,o = db.project_list[pid].get_outstanding_items()
    # print d
    # print o
    #
    fig = pyplot.figure()
    ax = fig.add_subplot(111)
    total_todos=pyplot.plot_date(sort(days), range(1,len(days)+1), 'o', xdate=True, ydate=False)
    #
    comp_todos=pyplot.plot_date(sort(days_comp), range(1,len(days_comp)+1), 'x', xdate=True, ydate=False)
    #
    outstand_todos = pyplot.plot_date(d, o, 'v', xdate=True, ydate=False)
    # outstand_todos = pyplot.bar(d, o, 10, color='red')
    ax.set_ylim([0,len(days)+2])
    ax.set_xlim([min(days)-2, max(days_comp)+2])
    ax.legend( (total_todos[0], comp_todos[0], outstand_todos[0]), ('Total Todos', 'Completed Todos', 'Outstanding'), 'upper center' )
    # ax.legend( (total_todos[0], comp_todos[0]), ('Total Todos', 'Completed Todos'), 'upper center' )
    
    fig.autofmt_xdate()
    pyplot.title("Todos created for Project: " + db.project_list[pid].title)
    
    print "=========================="
    print "Now try global all items plot: "
    glo_fig = pyplot.figure()
    ax2 = glo_fig.add_subplot(111)
    db.find_all_items()
    all_created = db.get_global_dates_created()
    all_completed = db.get_global_dates_completed()
    all_created_plot = pyplot.plot_date(sort(all_created), range(1, len(all_created)+1), 'o', xdate=True, ydate=False   )
    all_completed_plot = pyplot.plot_date(sort(all_completed), range(1, len(all_completed) + 1),'x', xdate=True, ydate=False  )
    ax2.legend( (all_created_plot[0], all_completed_plot[0]), ('Created Items', 'Completed Items'), 'upper left' )
    glo_fig.autofmt_xdate()
    pyplot.title("Items from all projects")
    
    
    pyplot.show()
    print "done. "
    return


if __name__ == '__main__':
    try:
        if(len(sys.argv) > 1):
            file = sys.argv[1]
        else:
            file = '../Database.xml'
        if(len(sys.argv) > 2):
            pid = int(sys.argv[2])
            main(file, pid)
        else:
            main(file)
    except IOError:
        print "syntax is: thingsplot.py /path/to/Database.xml [project_id_index]"
        raise
    except IndexError:
        print "Probably project_id_index has been set too high. "
        print "Current setting is: ", pid
        print "syntax is: thingsplot.py /path/to/Database.xml [project_id_index]"
        raise
    except:
        raise
    #